/**
 * 离线数据
 * Created by WMM on 2018/06/18.
 */
import { Component } from '@angular/core';
import { IonicPage, NavController, ToastController, NavParams, AlertController, App } from 'ionic-angular';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';

@IonicPage()
@Component({
  selector: 'page-offline-data',
  templateUrl: 'offline-data.html'
})
export class OfflineData {

  private MINyear: string;
  private MAXyear: string;
  private MINdate: string;
  private MAXdate: string;

  private now: Date;
  private past: Date;

  private loadOrUnloadObj: any;
  private loadOrUnloadList: Array<any>;

  private ruleRecordObj: any;
  private ruleRecordList: Array<any>;

  private exceptionInfoObj: any;
  private exceptionInfoList: Array<any>;


  private imgData: string = "assets/imgs/photo.jpg";


  //  页面即将进入时调用
  ionViewWillEnter() {
    this.getData(this.myFormat('yyyy-MM-dd hh:mm:ss', this.past), this.myFormat('yyyy-MM-dd hh:mm:ss', this.now));
  }


  constructor(private sqlite: SQLite, private app: App, public navCtrl: NavController, private alertCtrl: AlertController, public params: NavParams, private toastCtrl: ToastController) {
    this.now = new Date;
    this.past = new Date;
    this.past.setMonth(this.past.getMonth() - 1);
    this.MINyear = Number(this.now.getFullYear() - 2).toString();
    this.MAXyear = Number(this.now.getFullYear()).toString();
    this.MINdate = this.fixIsoDateString(this.past);
    this.MAXdate = this.fixIsoDateString(this.now);
    this.loadOrUnloadObj = {
      img: "",
      imgs: "",
      imgType: "",
      date: "",
      check: false,
      materielName: "",
      materielCode: "",
      containerName: "",
      containerCode: "",
      materielQrcode: "",
      materielId: "",
      pklmaterielId: "",
      containerId: "",
      containerQrcode: ""
    }
    this.ruleRecordObj = {
      img: "",
      materielQrcode: "",
      date: "",
      length: "",
      width: "",
      height: "",
      weight: "",
      description: "",
      materielId: "",
      pklmaterielId: "",
      check: false
    }
    this.exceptionInfoObj = {
      text: "",
      date: "",
      check: false
    };

  }

  timeSearch() {
    this.getData(this.myFormat('yyyy-MM-dd hh:mm:ss', new Date(this.fixIsoDateString(new Date(this.MINdate)))), this.myFormat('yyyy-MM-dd hh:mm:ss', new Date(this.fixIsoDateString(new Date(this.MAXdate)))));
  }


  getData(startTime: string, endTime: string) {
    this.loadOrUnloadList = [];
    this.ruleRecordList = [];
    this.exceptionInfoList = [];
    this.sqlite.create({
      name: 'ionicdb.db',
      location: 'default'
    }).then((db: SQLiteObject) => {
      //装卸货列表
      db.executeSql('SELECT T.* FROM (SELECT * from loadOrUnload WHERE date Between ? and ? ORDER BY date DESC)T GROUP BY T.containerQrcode,T.materielQrcode', [startTime, endTime])
        .then(res => {
          console.log('表loadOrUnload 查询完毕');
          if (res.rows.length > 0) {
            for (var i = 0; i < res.rows.length; i++) {
              ((i) => {
                this.cutImageBase64(this.imgbase64first(res.rows.item(i).img), "100", "100", (newImgData) => {
                  this.loadOrUnloadObj = {
                    img: newImgData,
                    imgs: res.rows.item(i).img,
                    imgType: res.rows.item(i).imgType,
                    date: res.rows.item(i).date,
                    materielName: res.rows.item(i).materielName,
                    materielCode: res.rows.item(i).materielCode,
                    containerName: res.rows.item(i).containerName,
                    containerCode: res.rows.item(i).containerCode,
                    materielQrcode: res.rows.item(i).materielQrcode,
                    materielId: res.rows.item(i).materielId,
                    pklmaterielId: res.rows.item(i).pklmaterielId,
                    containerId: res.rows.item(i).containerId,
                    containerQrcode: res.rows.item(i).containerQrcode,
                    check: false
                  }
                  this.loadOrUnloadList.push(this.loadOrUnloadObj);
                });
              })(i);
            }
          }
        }
        )
        .catch(e => console.log("系统Sql组件错误,请联系管理员!,错误信息为: " + e.message));
      //打尺检验列表
      db.executeSql('SELECT * FROM ruleRecord WHERE date Between ? and ?', [startTime, endTime])
        .then(res => {
          console.log('表ruleRecord 查询完毕');
          if (res.rows.length > 0) {
            for (var i = 0; i < res.rows.length; i++) {
              ((i) => {
                this.cutImageBase64(this.imgbase64first(res.rows.item(i).img), "100", "100", (newImgData) => {
                  this.ruleRecordObj = {
                    img: newImgData,
                    imgs: res.rows.item(i).img,
                    materielQrcode: res.rows.item(i).materielQrcode,
                    date: res.rows.item(i).date,
                    length: res.rows.item(i).length,
                    width: res.rows.item(i).width,
                    height: res.rows.item(i).height,
                    weight: res.rows.item(i).weight,
                    description: res.rows.item(i).description,
                    materielId: res.rows.item(i).materielId,
                    materielCode: res.rows.item(i).materielCode,
                    materielName: res.rows.item(i).materielName,
                    pklmaterielId: res.rows.item(i).pklmaterielId,
                    check: false
                  }
                  this.ruleRecordList.push(this.ruleRecordObj);
                });
              })(i);
            }
          }
        })
        .catch(e => console.log("系统Sql组件错误,请联系管理员!,错误信息为: " + e.message));
      //异常信息列表
      db.executeSql('SELECT * FROM exceptionReport WHERE date Between ? and ? ', [startTime, endTime])
        .then(res => {
          console.log('表exceptionReport 查询完毕');
          if (res.rows.length > 0) {
            for (var i = 0; i < res.rows.length; i++) {
              this.exceptionInfoObj = {
                text: res.rows.item(i).exception,
                date: res.rows.item(i).date,
                check: false
              }
              this.exceptionInfoList.push(this.exceptionInfoObj);
            }
          }
        })
        .catch(e => console.log("系统Sql组件错误,请联系管理员!,错误信息为: " + e.message));
    }).catch(e =>
      this.showMsg("系统Sql组件错误,请联系管理员!,错误信息为: " + e)
    );
  }

  selectAll(type: string) {
    if (type == "loadOrUnload") {
      this.loadOrUnloadList.forEach(item => {
        item.check = true;
      })
    } else if (type == "ruleRecord") {
      this.ruleRecordList.forEach(item => {
        item.check = true;
      })
    } else if (type == "exceptionReport") {
      this.exceptionInfoList.forEach(item => {
        item.check = true;
      })
    } else {
      this.showMsg("非法操作,参数错误");
    }
  }


  logIn() {
    let alert = this.alertCtrl.create({
      title: '使用在线功能请确保网络通畅!',
      message: "点击确定将进入登录页面!",
      buttons: ['取消',
        {
          text: '确定',
          handler: data => {
            //点击确定,跳转到登录页面
            this.app.getRootNav().push('LoginPage', { "backButtontag": true });//用this.app.getRootNav() 从根页面跳转
          }
        }]
    });
    alert.present();
  }


  goDataUpload() {
    //将所有参数传递给下一个界面
    if (this.loadOrUnloadList.filter(item => item.check === true).length == 0 &&
      this.ruleRecordList.filter(item => item.check === true).length == 0 &&
      this.exceptionInfoList.filter(item => item.check === true).length == 0) {
      this.showMsg("请至少选择一项!");
    } else {
      this.navCtrl.push("DataUpload", {
        "loadOrUnloadList": this.loadOrUnloadList.filter(item => item.check === true),
        "ruleRecordList": this.ruleRecordList.filter(item => item.check === true),
        "exceptionInfoList": this.exceptionInfoList.filter(item => item.check === true)
      });
    }
  }

  //点击取消返回
  goBack() {
    this.navCtrl.pop();
  }

  showMsg(msg: string) {
    var toast = this.toastCtrl.create({
      message: msg,
      duration: 3000,
      position: 'bottom'
    });
    toast.present();
  }


  imgbase64first(base64: string) {
    if (base64 != null && base64 != "") {
      let imgbase64: Array<string> = base64.split("!");
      return imgbase64[0];
    } else {
      return this.imgData;
    }
  }


  myFormat(fmt: string, data: Date) {
    var o = {
      "M+": data.getMonth() + 1,                 //月份
      "d+": data.getDate(),                    //日
      "h+": data.getHours(),                   //小时
      "m+": data.getMinutes(),                 //分
      "s+": data.getSeconds(),                 //秒
      "q+": Math.floor((data.getMonth() + 3) / 3), //季度
      "S": data.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
      fmt = fmt.replace(RegExp.$1, (data.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
      if (new RegExp("(" + k + ")").test(fmt))
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
  }

  fixIsoDateString(date: Date) {
    let ISOdata = new Date(date);
    ISOdata.setHours(date.getHours(), date.getMinutes() - date.getTimezoneOffset());
    return ISOdata.toISOString();
  }

  isEmpty(obj) {
    if (!obj && obj !== 0 && obj !== '') {
      return true;
    }
    if (Array.prototype.isPrototypeOf(obj) && obj.length === 0) {
      return true;
    }
    if (Object.prototype.isPrototypeOf(obj) && Object.keys(obj).length === 0) {
      return true;
    }
    return false;
  }

  cutImageBase64(base64: string, width: string, height: string, callback) {
    let newbase64: string;
    if (base64 == "assets/imgs/photo.jpg" || base64 == "") {
      newbase64 = "assets/imgs/photo.jpg";
      callback ? callback(newbase64) : null; //调用回调函数
    } else {
      let _img = new Image();
      _img.src = base64;
      _img.onload = function () {
        let _canvas = document.createElement("canvas");
        _canvas.setAttribute("width", width);
        _canvas.setAttribute("height", height);
        _canvas.getContext("2d").drawImage(_img, 0, 0, Number(width), Number(height));
        newbase64 = _canvas.toDataURL("image/jpeg");
        callback ? callback(newbase64) : null; //调用回调函数
      }
    }
  }


}
